﻿using MQTTnet.Client.Connecting;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Packets;
using Microsoft.Extensions.Configuration;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;

namespace PHMEE.Admin
{
    public class MqttExtendAppService : PHMEEAdminAppService, IMqttExtendAppService
    {
        private readonly IConfiguration _configuration;
        private readonly IMqttClientOptions _options;
        private readonly IMqttFactory _mqttFactory;
        private IMqttClient _mqttClient;
        private readonly ILogger<MqttExtendAppService> _logger;

        public MqttExtendAppService(IConfiguration configuration, ILogger<MqttExtendAppService> logger)
        {
            _configuration = configuration;
            _logger = logger;
            _mqttFactory = new MqttFactory();
            string Server = _configuration.GetValue<string>("MqttClient:Host")!;
            int Port = _configuration.GetValue<int>("MqttClient:Port")!;
            string username = _configuration.GetValue<string>("MqttClient:UserName")!;
            string password = _configuration.GetValue<string>("MqttClient:Password")!;
            _options = new MqttClientOptionsBuilder()
                .WithClientId(Guid.NewGuid().ToString())
                .WithCredentials(username, password)
                .WithCleanSession(true)
                .WithTcpServer(Server, Port)
                .Build();
        }
        /// <summary>
        /// 执行发送消息的逻辑，并自动处理连接
        /// </summary>
        public async Task<bool> SendMessageAsync(string topic, string payload)
        {
            try
            {
                if (await ExecuteMqttClientAsync())
                {
                    _logger.LogInformation($"MQTT 发送消息到主题: {topic}");
                    await _mqttClient.PublishAsync(new MqttApplicationMessage
                    {
                        Topic = topic,
                        Payload = Encoding.UTF8.GetBytes(payload),
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce
                    });
                    return true;
                }
                else
                {
                    _logger.LogWarning("MQTT 连接失败，无法发送消息。");
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"发送消息时出错: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 确保 MQTT 客户端连接正常
        /// </summary>
        private async Task<bool> ExecuteMqttClientAsync()
        {
            try
            {
                if (_mqttClient == null || !_mqttClient.IsConnected)
                {
                    _mqttClient = _mqttFactory.CreateMqttClient();
                    var result = await _mqttClient.ConnectAsync(_options);
                    return result.ResultCode == MqttClientConnectResultCode.Success;
                }
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError($"MQTT 连接失败: {ex.Message}");
                return false;
            }
        }
    }
}
